'''
文档查重程序入口
'''
import json

from tqdm import tqdm
from util import embed_sentences_by_bert_serving, sort_standard_names, read_xlsx
from converter import convert


def compute(input):
    print('input:', input)

    # 读取数据
    print('reading data...')
    standard_names, checked_names = read_xlsx(input)

    # 使用bert编码句子
    print('embedding sentences...')
    standard_names_embedd = embed_sentences_by_bert_serving(standard_names)
    checked_names_embedd = embed_sentences_by_bert_serving(checked_names)

    # 使用余弦相似度计算句子相似度
    res = []  # [{"target":"","source":[{"sent":"","score":""}]}]
    print('computing similarity...')

    for idx in tqdm(range(len(checked_names))):
        sort_result = sort_standard_names(standard_names, standard_names_embedd, checked_names_embedd[idx])
        target = checked_names[idx]

        source = []
        # for idy, r in enumerate(sort_result):
        # if idy > 0:
        #     break
        # source.append({"sent": r[0], "score": '%.3f' % (r[1])})
        source = sort_result[0][0]
        score = sort_result[0][1]

        res.append({"target": target, "source": source, "score": '%.3f' % score})
    # 将句子根据相似度得分排序
    res = sorted(res, key=lambda item: item['score'], reverse=True)

    # 将结果保存至json_out.json
    with open("out/json_out.json", "w") as f:
        json.dump(res, f, ensure_ascii=False)


def interface(input, output):
    # 计算相似度
    compute(input)
    # 将结果转换为HTML并返回
    convert(output)


if __name__ == '__main__':
    # input ./data/sample.xlsx
    # output out/result.html
    interface('./data/sample.xlsx', './out/result.html')
